<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\util\ReturnCode;
use support\Response;

class Index extends Base
{

    public function upload(): Response
    {
        $request = request();
        $path =public_path(). '/upload/' . date('Ymd', time()) . '/';
        $file_sys = $request->file('file');
        $name = $file_sys->getFilename();
        $error =  $file_sys->getUploadErrorCode();
        //过滤错误
        if ($error) {
            switch ($error) {
                case 1:
                    $error_message = '您上传的文件超过了PHP.INI配置文件中UPLOAD_MAX-FILESIZE的大小';
                    break;
                case 2:
                    $error_message = '您上传的文件超过了PHP.INI配置文件中的post_max_size的大小';
                    break;
                case 3:
                    $error_message = '文件只被部分上传';
                    break;
                case 4:
                    $error_message = '文件不能为空';
                    break;
                default:
                    $error_message = '未知错误';
            }
            return $this->buildFailed(ReturnCode::FILE_SAVE_ERROR, $error_message);
        }
        $arr_name = explode('.', $name);
        $hz = array_pop($arr_name);
        $new_name = md5(time() . uniqid()) . '.' . $hz;
        if ($file_sys && $file_sys->isValid()) {
            $file_sys->move(public_path().'/files/'.$new_name.'.'.$file_sys->getUploadExtension());
            return $this->buildSuccess([
                'fileName' => $new_name,
                'fileUrl' => 'http://'.$request->host().'/files/'.$new_name.'.'.$file_sys->getUploadExtension()
            ]);
        }
        return $this->buildFailed(ReturnCode::FILE_SAVE_ERROR, '文件上传失败');

    }
}
